from flask import Flask, jsonify
from flask_apscheduler import APScheduler
from flask_cors import CORS

import APSchedulerJobConfig
from App.Admin import Admin
from App.Api import Api
from App.Html import Html

scheduler = APScheduler()


def create_app():
    app = JsonFlask(__name__)
    app.register_blueprint(Api)
    app.register_blueprint(Admin)
    app.register_blueprint(Html)
    app.config.from_object('config')
    app.config.from_object(APSchedulerJobConfig)
    scheduler.init_app(app)
    scheduler.start()
    if app.debug:  # 调试模式下允许跨域
        CORS(app, supports_credentials=True)
    return app


class JsonResponse(object):
    def __init__(self, data, code, msg):
        self.data = data
        self.code = code
        self.msg = msg

    @classmethod
    def success(cls, *args):
        params = [None, 200, "OK"]
        i = 0
        for val in args:
            params[i] = val
            i = i + 1
        return cls(params[0], params[1], params[2])

    def to_dict(self):
        return {
            "code": self.code,
            "msg": self.msg,
            "data": self.data,
        }


class JsonFlask(Flask):
    def make_response(self, rv):
        if rv is None or isinstance(rv, (list, dict)):
            the_data = (rv,)
            rv = JsonResponse.success(*the_data)

        if isinstance(rv, (tuple)):
            rv = JsonResponse.success(*rv)

        if isinstance(rv, JsonResponse):
            rv = jsonify(rv.to_dict())
        return super().make_response(rv)
